package com.itdfq.dingding.utils;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author: QianMo
 * @date: 2022/2/11 10:06
 * @mark:
 */

public class HttpUtil {

    public static String doGet(String getUrl, Map<String, Object> headParam) {
        String realUrl = getUrl;
        try {
            // 1.通过在 URL 上调用 openConnection 方法创建连接对象
            URL url = new URL(realUrl);
            URLConnection conn = url.openConnection();
            // 2.处理设置参数和一般请求属性
            // 2.1设置参数
            // 可以根据请求的需要设置参数
            conn.setUseCaches(false);
            // 请求超时时间
            conn.setConnectTimeout(5000);
            // 2.2请求属性
            // 设置通用的请求属性 更多的头字段信息可以查阅HTTP协议
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            if (headParam != null && headParam.size() > 0) {
                for (String key : headParam.keySet()) {
                    conn.setRequestProperty("key", JSON.toJSONString(headParam.get(key)));
                }
            }
            // 3.使用 connect 方法建立到远程对象的实际连接。
            conn.connect();
            // 4.远程对象变为可用。远程对象的头字段和内容变为可访问。
            // 4.1获取响应的头字段
            Map<String, List<String>> headers = conn.getHeaderFields();
            // 4.2获取响应正文
            BufferedReader reader = null;
            StringBuffer resultBuffer = new StringBuffer();
            String tempLine = null;

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            reader.close();
            return resultBuffer.toString();
        } catch (Exception e) {
            throw new RuntimeException("请求异常");
        }
    }


    public static String doPost(String url, String param, Map<String, Object> headParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //Header中存几个自己用的参数
            if (headParam != null && headParam.size() > 0) {
                for (String key : headParam.keySet()) {
                    conn.setRequestProperty("key", JSON.toJSONString(headParam.get(key)));
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);

            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw new RuntimeException("请求异常");
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}
